﻿using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace _063.Sleep的替代
{
	internal class Program
	{
		static async Task Main(string[] args)
		{
			await DownloadAsync("https://www.baidu.com", @"d:\1.txt");
			await Console.Out.WriteLineAsync("ok");
		}

		/**
		 * 下载
		 */
		static async Task<int> DownloadAsync(string url, string destFilePath)
		{
			string body;
			using (HttpClient httpClient = new HttpClient())
			{
				body = await httpClient.GetStringAsync(url);
				//等待1秒 页面不会卡死 不会阻塞主线程
				await Task.Delay(1000);
			}
			await File.WriteAllTextAsync(destFilePath, body);
			return body.Length;
		}

		/**
		 * 下载  失败就等待  等待三次之后 抛出异常
		 */
		static async Task<string> DownLoadHtmlAsync2(string url, int init = 0)
		{
			try
			{
				using (var client = new HttpClient())
				{
					var res = await client.GetStringAsync(url);
					return res;

				}
			}
			catch (Exception e)
			{
				init++;
				if (init >= 3)
				{
					throw new Exception("time out");
				}
				await Task.Delay(500);
				await DownLoadHtmlAsync2(url, init);

				return "time out";
			}
		}
	}
}
